package tp1.presentacion.controlador;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import tp1.presentacion.modelo.Localidad;
import tp1.presentacion.modelo.LocalidadLogic;
import tp1.presentacion.modelo.Provincia;
import tp1.presentacion.modelo.ProvinciaLogic;

/**
 * Servlet implementation class LocalidadController
 */
public class LocalidadController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LocalidadController() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String url = request.getPathInfo();
		if(url.equals("/listar")) {
			this.listarLocalidades(request, response);
		} else if(url.equals("/nuevo")) {
			response.sendRedirect("nuevaLoc.jsp");
		} else if(url.equals("/registrar")) {
			this.registrarLocalidad(request, response);
		}
	}
	
	private void registrarLocalidad(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String nombre = request.getParameter("nomLoc");
		int distancia = Integer.parseInt(request.getParameter("distancia"));
		int cod_prov = Integer.parseInt(request.getParameter("provincias"));
		ProvinciaLogic pLog = new ProvinciaLogic();
		Provincia provincia = pLog.getUno(cod_prov);
		Localidad loc = new Localidad();
		loc.setCodigo(0);
		loc.setNombre(nombre);
		loc.setDistancia(distancia);
		loc.setProvincia(provincia);
		LocalidadLogic locLog = new LocalidadLogic();
		locLog.agregar(loc);
		response.sendRedirect("index.jsp");
	}
	private void listarLocalidades(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		LocalidadLogic locLog = new LocalidadLogic();
		ArrayList<Localidad> locs = locLog.getTodos();
		request.setAttribute("locs", locs);
		RequestDispatcher rdis = request.getRequestDispatcher("/listLocs.jsp");
		rdis.forward(request, response);		
	}

}
